package com.yeban.javase.day19.answer.test4;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/11/4
 */
public class WriteThread implements Runnable {

    private Socket socket;
    private CountDownLatch countDownLatch;

    public WriteThread(Socket socket, CountDownLatch countDownLatch) {
        this.socket = socket;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try(
            PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
            Scanner sc = new Scanner(System.in);
        ) {
            while(true) {
                System.out.println("请说：");
                String msg = sc.nextLine();
                pw.println(msg);

                if(msg.equals("exit")) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            countDownLatch.countDown();
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
